let query = {
  pagenum: 1,
  pagesize: 2,
  cate_id: '',
  state: ''
}
fn()
function fn() {
  axios.get('/my/article/list', {
    params: query,
  })
    .then(({ data: { data, total } }) => {
      // console.log(data);
      let newArr = data.map(({ title, cate_name, pub_date, state, Id }) =>
        `
        <tr>
        <td>${title}</td>
        <td>${cate_name}</td>
        <td>${pub_date}</td>
        <td>${state}</td>
        <td>
          <button type="button" class="layui-btn layui-btn-xs btn_edit" data-id="${Id}">编辑</button>
          <button type="button" class="layui-btn layui-btn-danger layui-btn-xs btn_delete" data-id="${Id}">删除</button>
          </td>
      </tr>
        `
      )
      $('#list').html(newArr.join(''))
      renderPage(total)
    });
}

const form = layui.form
axios.get('/my/article/cates').then((res) => {
  let newArr = res.data.data.map((item) => {
    return `<option value="${item.Id}">${item.name}</option>`
  })
  $('#cateSelect').html(
    '<option value="">所有分类</option>' + newArr.join('')
  )
  form.render()
})

$('#form').on('submit', function (e) {
  e.preventDefault()
  query.cate_id = $('#cateSelect').val()
  query.state = $('#stateSelect').val()
  query.pagenum = 1
  fn()
})


const laypage = layui.laypage
function renderPage(count) {
  //执行一个laypage实例
  laypage.render({
    elem: 'page-box' //注意，这里的 test1 是 ID，不用加 # 号
    , count, //数据总数，从服务端得到
    limit: query.pagesize,
    limits: [1, 2, 3, 5, 8, 10],
    curr: query.pagenum,
    layout: ['count', 'limit', 'prev', 'page', 'next', 'skip'],
    jump: function (obj, first) {
      // console.log(obj.curr);
      query.pagenum = obj.curr

      query.pagesize = obj.limit
      if (!first) {
        fn()
      }
    }
  });
}
$('#list').on('click', '.btn_delete', function () {
  let id = $(this).attr('data-id')
  layer.confirm(
    '确定删除此文章吗?',
    { icon: 3, title: '提示' },
    function (index) {
      axios.get('/my/article/delete/' + id).then((res) => {
        console.log(res);
        if (res.data.status !== 0) {
          return layer.msg(res.data.message)
        }
        if ($('.btn_delete').length === 1) {
          query.pagenum = query.pagenum === 1 ? 1 : query.pagenum - 1
        }
        layer.msg(res.data.message)
        layer.close(index)
        fn()
      })
    }
  )
})